package com.bingo.mpa.service;

import java.util.LinkedList;

import com.bingo.mpa.dao.LogDao;
import com.bingo.mpa.pojo.Log;

public class LogService extends Thread
{
	private static class SingletonHolder {
		private static final LogService INSTANCE = new LogService();
	}

	private LogService() {
	}

	public static final LogService getInstance() {
		return SingletonHolder.INSTANCE;
	}

	private boolean running = true;
	private LinkedList<Log> queue = new LinkedList<Log>();

	public synchronized void close() {
		running = false;
		this.notify();
	}
	
	@Override
	public void run() {
		Log obj = null;
		while (running) 
		{
			synchronized (this) 
			{
				if (this.queue.isEmpty())
				{
					try 
					{
						this.wait();
						continue;
					} 
					catch (InterruptedException e) 
					{
						e.printStackTrace();
					}
				} 
				else 
				{
					obj = queue.poll();
					try 
					{
						if (obj == null)
						{
							continue;
						}
						LogDao.saveLog(obj);
						
					} catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
		}
	}

	public synchronized void write(Log obj) {
		queue.offer(obj);
		if (!this.isAlive()) {
			this.start();
		}
		this.notify();
	}
}
